package session_notifications

import (
	"context"
	"github.com/gorpher/gowin32"
	"github.com/sirupsen/logrus"
	"hcy-api/lib/utils"
	"hcy-api/structs/base"
	"hcy-api/structs/enum"
	"hcy-api/structs/vap"
	"time"
	"vap_host/daemon/tcp"
)

func Call(ctx context.Context, tcpClient *tcp.Client) (err error) {
	chanMsg := make(chan Message, 100)
	Subscribe(chanMsg, ctx)
	for {
		select {
		case <-ctx.Done():
			return nil
		case m := <-chanMsg:
			var msg vap.WinSessionChangeMsg
			var notify bool // 登录、断开、注销 时需要给服务端发送消息
			wtsServer := gowin32.OpenWTSServer("")
			msg.Username, err = wtsServer.QuerySessionUserName(uint(m.LParam))
			if err != nil {
				return err
			}
			msg.WinSessionId = m.LParam
			msg.WtsCode = m.WParam
			switch m.UMsg {
			case WM_WTSSESSION_CHANGE:
				switch m.WParam {
				case WTS_CONSOLE_CONNECT:
					msg.Describe = "WTS_CONSOLE_CONNECT：标识的会话已连接"
				case WTS_CONSOLE_DISCONNECT:
					msg.Describe = "WTS_CONSOLE_DISCONNECT：标识的会话已断开连接"
				case WTS_REMOTE_CONNECT:
					msg.Describe = "WTS_REMOTE_CONNECT：标识的会话已连接到远程终端"
				case WTS_REMOTE_DISCONNECT:
					msg.Describe = "WTS_REMOTE_DISCONNECT：标识的会话已与远程终端断开连接"
					notify = true
				case WTS_SESSION_LOGON:
					msg.Describe = "WTS_SESSION_LOGON：用户已登录到标识的会话"
					notify = true
				case WTS_SESSION_LOGOFF:
					msg.Describe = "WTS_SESSION_LOGOFF：用户已注销标识的会话"
					notify = true
				case WTS_SESSION_LOCK:
					msg.Describe = "WTS_SESSION_LOCK：标识的会话已被锁定"
				case WTS_SESSION_UNLOCK:
					msg.Describe = "WTS_SESSION_UNLOCK：标识的会话已解锁"
				case WTS_SESSION_REMOTE_CONTROL:
					msg.Describe = "WTS_SESSION_REMOTE_CONTROL：标识的会话已更改其远程控制状态"
				}
			case WM_QUERYENDSESSION:
				msg.Describe = "WM_QUERYENDSESSION：不知道具体含义的状态，需要排查"
			}
			if notify {
				in := base.ClientResponse{
					Result:     utils.Obj2Str(msg),
					ResultType: enum.WinSessionChange,
					MsgTime:    time.Now().Unix(),
				}
				err = tcpClient.WriteMessage(in)
				if err != nil {
					logrus.Error(err)
				}
			}
			close(m.ChanOk)
		}
	}
}
